/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View;

import java.awt.Image;
import java.awt.Toolkit;
import java.sql.ResultSet;
import java.util.Calendar;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

/**
 *
 * @author Antonio
 */
public class Home extends javax.swing.JFrame {

    int dia;
    int mes;
    int annio;
    String date;
    int idrun;
    int maxblock;
            
    /**
     * Creates new form Home
     */
    public Home() {
       // setUndecorated(true); para elminar los botones maximizar minimizar cerrar
        initComponents();
       this.setResizable(false); //inabilita boton de maximizar
        fecha();
      //  setDefaultCloseOperation(0); // para desabilitar el boton de cerrar la aplicacion igual lo muestra
    }

    
        @Override
    public Image getIconImage() {
        Image retValue = Toolkit.getDefaultToolkit().
                getImage(ClassLoader.getSystemResource("image/logo.png"));
       return retValue;
    }

   private int getMaxBlock(int idrun){
       ResultSet rs;
       Conexion conexion = new Conexion();
       conexion.starConexion();
       String query = "select max(block) from product where fk_run='"+idrun+"'";
       rs = conexion.excecuteresult(query);
        try{
        while (rs.next())
        {
          maxblock = rs.getInt(1);
            System.out.println(" el Maximo bloque es: "+ maxblock);
        }
        } catch(Exception e)
        {
            System.out.println("Problema al consultar con la BD"+e.getMessage());
        }
        conexion.closeConexion();
        return(maxblock);
   }
        
    private int getidRunHome(String date)
    {
        ResultSet rs;
        Conexion conexion = new Conexion();
        conexion.starConexion();
        String query = "select id from run where date = '"+date+"'";
     //   System.out.println(query);
        rs = conexion.excecuteresult(query);
        try{
        while (rs.next())
        {
          idrun = rs.getInt(1);
            System.out.println(" el ID de la corrida es: "+ idrun);
        }
        } catch(Exception e)
        {
            System.out.println("Problema al imprimir la base de datos "+e.getMessage());
        }
        conexion.closeConexion();
        return(idrun);
    }

public void fecha()
{
        Calendar c1 = Calendar.getInstance();
        
         dia = (c1.get(Calendar.DATE));
         mes = (c1.get(Calendar.MONTH)+1);
        annio =(c1.get(Calendar.YEAR));    
        date= annio+"-"+mes+"-"+dia;
}
        
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButtonGenerate = new javax.swing.JButton();
        jButtonRun = new javax.swing.JButton();
        jButtonExit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setIconImage(getIconImage());
        setMaximumSize(new java.awt.Dimension(800, 600));
        setMinimumSize(new java.awt.Dimension(800, 600));

        jButtonGenerate.setText("Generate");
        jButtonGenerate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGenerateActionPerformed(evt);
            }
        });

        jButtonRun.setText("Run");
        jButtonRun.setPreferredSize(new java.awt.Dimension(200, 500));
        jButtonRun.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRunActionPerformed(evt);
            }
        });

        jButtonExit.setLabel("Exit");
        jButtonExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(298, 298, 298)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButtonExit, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonGenerate, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonRun, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(287, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(85, 85, 85)
                .addComponent(jButtonRun, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(84, 84, 84)
                .addComponent(jButtonGenerate, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(84, 84, 84)
                .addComponent(jButtonExit, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(95, Short.MAX_VALUE))
        );

        jButtonExit.getAccessibleContext().setAccessibleName("E");

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonGenerateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGenerateActionPerformed
        Generate generate  = new Generate();
        generate.setVisible(true);
        this.setVisible(false); 
                
    }//GEN-LAST:event_jButtonGenerateActionPerformed

    private void jButtonRunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRunActionPerformed
         idrun = getidRunHome(date);
        
         if (idrun==0){
            Run run = new Run();
            run.setVisible(true);
            this.setVisible(false); 
         }
         else{
             maxblock=getMaxBlock(idrun);
             maxblock++;
             JOptionPane.showMessageDialog(null,"Run already exists for today","Run",1);
             System.out.println("max bloque"+maxblock+" id corrida "+idrun);
             Run run = new Run(maxblock, idrun);
             run.setVisible(true);
             this.setVisible(false);
         }
            
         
        
        // TODO add your handling code here:
    }//GEN-LAST:event_jButtonRunActionPerformed

    private void jButtonExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExitActionPerformed
      System.exit(0);
    }//GEN-LAST:event_jButtonExitActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                      
            try{
            JFrame.setDefaultLookAndFeelDecorated(true);
            JDialog.setDefaultLookAndFeelDecorated(true);
          //  UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel"); 
           //  UIManager.setLookAndFeel("com.jtattoo.plaf.graphite.GraphiteLookAndFeel");
            // UIManager.setLookAndFeel("com.jtattoo.plaf.fast.FastLookAndFeel"); menos
          //  UIManager.setLookAndFeel("com.jtattoo.plaf.mint.MintLookAndFeel"); //Medium
            UIManager.setLookAndFeel("com.jtattoo.plaf.aero.AeroLookAndFeel"); //Medium
            //  UIManager.setLookAndFeel("com.jtattoo.plaf.mcwin.McWinLookAndFeel");  //Menos
            //   UIManager.setLookAndFeel("com.jtattoo.plaf.luna.LunaLookAndFeel"); //menos
            }
            
            catch (Exception e){
            e.printStackTrace();
            }              
                new Home().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonExit;
    private javax.swing.JButton jButtonGenerate;
    private javax.swing.JButton jButtonRun;
    // End of variables declaration//GEN-END:variables
}
